<template>
  <div class="scene_box">
    <p>加载外部gltf文件，解决渲染颜色出现偏差的问题</p>
    <div class="canvas"></div>
  </div>
</template>
        
   <script setup>
import { nextTick } from "vue";
import gltf from "./gongchang.gltf";
import * as THREE from "three";
// 引入threejs 的扩展库  相机轨道控件
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// 引入gltf模型加载库GLTFLoader.js
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";

nextTick(() => {
  // ******************创建一个场景*************

  const loader = new GLTFLoader(); //创建一个GLTF加载器

  const model = new THREE.Group(); //声明一个组对象，用来添加加载成功的三维场景

  loader.load(gltf, function (gltf) {
    //gltf加载成功后返回一个对象
    // console.log('控制台查看gltf对象结构', gltf);
    // console.log('场景3D模型数据', gltf.scene);
    model.add(gltf.scene); //三维场景添加到model组对象中
  });

  // ————————————————————————————————————————————————————————————————————————————————
  //场景
  const scene = new THREE.Scene();
  scene.add(model); //模型对象添加到场景中

  //辅助观察的坐标系
  const axesHelper = new THREE.AxesHelper(150);
  scene.add(axesHelper);
  //光源设置
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(-200, 200, -200);
  scene.add(directionalLight);
  const ambient = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambient);

  //渲染器和相机
  let dom = document.querySelector(".canvas");
  const width = dom.offsetWidth;
  const height = dom.offsetHeight;
  const camera = new THREE.PerspectiveCamera(50, width / height, 1, 1000);
  camera.position.set(-100, 50, 50);
  camera.lookAt(0, 0, 0);

  const renderer = new THREE.WebGLRenderer({
    antialias: true, //去除锯齿
  });
  renderer.setSize(width, height);
  dom.appendChild(renderer.domElement);

  // ————————————————————————————————————————————————————————————————————————————————
  //设置编码方式和gltf贴图保持一致，解决渲染颜色出现偏差的问题
  renderer.outputEncoding = THREE.sRGBEncoding;
  // 渲染循环
  function render() {
    // scene.rotateY(0.005);
    renderer.render(scene, camera);
    requestAnimationFrame(render);
    // console.log(camera.position, "相机定位");
  }
  render();

  const controls = new OrbitControls(camera, renderer.domElement);

  // 画布跟随窗口变化
  window.onresize = function () {
    renderer.setSize(dom.offsetWidth, dom.offsetHeight);
    camera.aspect = dom.offsetWidth / dom.offsetHeight;
    camera.updateProjectionMatrix();
  };
  renderer.setPixelRatio(window.devicePixelRatio);
});
</script>
        
        
  <style  scoped>
.canvas {
  width: 80vw;
  height: 60vh;
}
</style>